package com.baidu.mapapi

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import kotlin.math.abs

class MyOrientationListener(private val mContext: Context) : SensorEventListener {
    private var mSensorManager: SensorManager? = null
    private var mSensor: Sensor? = null
    private var lastX = 0f
    private var mOnOrientationListener: OnOrientationListener? = null

    fun setmOnOrientationListener(mOnOrientationListener: OnOrientationListener?) {
        this.mOnOrientationListener = mOnOrientationListener
    }

    fun start() {
        mSensorManager = mContext
                .getSystemService(Context.SENSOR_SERVICE) as SensorManager
        if (mSensorManager != null) {
            //获得方向传感器
            mSensor = mSensorManager!!.getDefaultSensor(Sensor.TYPE_ORIENTATION)
        }
        if (mSensor != null) {
            mSensorManager!!.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI)
        }
    }

    fun stop() {
        //停止定位
        mSensorManager!!.unregisterListener(this)
    }

    override fun onSensorChanged(event: SensorEvent) {
        if (event.sensor.type == Sensor.TYPE_ORIENTATION) {
            val x = event.values[SensorManager.DATA_X]
            if (abs(x - lastX) > 1.0) {
                if (mOnOrientationListener != null) {
                    mOnOrientationListener!!.onOrientationChanged(x)
                }
            }
            lastX = x
        }
    }

    override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}

    interface OnOrientationListener {
        fun onOrientationChanged(x: Float)
    }
}